var PROJECT_ITEM_MAP = {}
var PROJECT_MAP = {}
var CUSTOM_PROP_LABEL = 'com.sobey.adobe.prop'

$._pr_ = {
  ping: function () {
    return 'success'
  },

  clearCache: function () {
    app.enableQE();
    var MediaType_ANY = 'FFFFFFFF-FFFF-FFFF-FFFF-FFFFFFFFFFFF';
    qe.project.deletePreviewFiles(MediaType_ANY);
  },
  setEnableTranscodeOnIngest: function (value) {
    // 是否需要将app的上的api直接映射到js app[api](value)
    if (parseFloat(app.version) >= 14) {
      app.setEnableTranscodeOnIngest(value);
    }
  },
  getActiveSequence: function () {
    return $._.clone(app.project.activeSequence)
  },
  saveProject: function () {
    $._.setEnableTranscodeOnIngest(false);
    return app.project.save();
  },
  getProject: function () {
    // 尽量把信息聚合在js端来做逻辑？
    function deepSearchProjectItem (item, outItem) {
      for (var i = 0; i < item.children.numItems; i++) {
        var projectItem = item.children[i];
        var copiedProjectItem = $._.clone(projectItem)
        delete copiedProjectItem.getOverrideColorSpaceList // 这个数据太大了
        PROJECT_ITEM_MAP[copiedProjectItem.nodeId] = projectItem // for query
        if (projectItem && projectItem.type === ProjectItemType.BIN) {
          copiedProjectItem.children = []
          deepSearchProjectItem(projectItem, copiedProjectItem);
        }
        outItem.children.push(copiedProjectItem)
      }
    }

    var rootItem = $._.clone(app.project.rootItem)
    rootItem.children = []
    var copiedProject = $._.clone(app.project)
    copiedProject.rootItem = rootItem
    deepSearchProjectItem(app.project.rootItem, rootItem);

    return copiedProject
  },
  closeProjectByPath: function (path) {
    // 是否需要换种方式
    if (app.project) {
      for (var i = 0; i < app.projects.numProjects; i++) {
        var currentProject = app.projects[i];
        var project = currentProject.path;
        if (project.substring(0, 4) == '\\\\?\\') {
          project = project.substring(4, project.length);
        }
        if (project === path) {
          currentProject.closeDocument();
        }
      }
    }
  },
  // 需要将error字符串定义一下
  openProject: function (projectPath) {
    var file = new File(unescape(projectPath));
    if (file && file.exists) {
      if (app.isDocument(projectPath)) {
        if (app.isDocumentOpen()) {
          return 'project has openned'
        } {
          app.openDocument(file.fsName, 1, 1, 1);
          file.close();
          return $._.clone(app.project);
        }
      } {
        return 'not project'
      }
    } else {
      return 'not exists'
    }
  },
  openFCPXML: function (filePath) {
    var file = new File(unescape(filePath));
    if (file && file.exists) {
      app.openDocument(file.fsName, 1, 1, 1);
      file.close();
      return $._.clone(app.project);
    } else {
      return 'not exists'
    }
  },
  setPlayerPosition: function (timecode) {
    var tick = unescape(timecode);
    app.enableQE();
    var qeSeq = qe.project.getActiveSequence();
    qeSeq.player.scrubTo(tick);
  },
  saveAsProject: function (fullPath) {
    $._PPP_.setEnableTranscodeOnIngest(false);
    app.project.saveAs(fullPath);
  },
  getAppLocation: function () {
    return qe.location;
  },
  getMetadata: function (id, key) {
    var projectItem = PROJECT_ITEM_MAP[id]
    if (!projectItem) {
      return 'not exists'
    }
    var kPProPrivateProjectMetadataURI = 'http://ns.adobe.com/premierePrivateProjectMetaData/1.0/';
    var projectMetadata = projectItem.getProjectMetadata();
    var xmp = new XMPMeta(projectMetadata);
    if (xmp.doesPropertyExist(kPProPrivateProjectMetadataURI, key)) {
      return xmp.getProperty(kPProPrivateProjectMetadataURI, key)
    } else {
      return 'not exists'
    }
  },
  setMetadata: function (id, key, value) {
    var projectItem = PROJECT_ITEM_MAP[id]
    if (!projectItem) {
      return 'not exists'
    }
    var kPProPrivateProjectMetadataURI = 'http://ns.adobe.com/premierePrivateProjectMetaData/1.0/';
    var projectMetadata = projectItem.getProjectMetadata();
    var xmp = new XMPMeta(projectMetadata);
    app.project.addPropertyToProjectMetadataSchema(key, CUSTOM_PROP_LABEL, 2);
    xmp.setProperty(kPProPrivateProjectMetadataURI, key, value);
    projectItem.setProjectMetadata(xmp.serialize(), [key]);
  },
  changeMediaPath: function (id, path) {
    var projectItem = PROJECT_ITEM_MAP[id]
    if (!projectItem) {
      return 'not exists'
    }
    if (!projectItem.canChangeMediaPath()) {
      return 'not support'
    }
    var interp = projectItem.getFootageInterpretation();
    var result = projectItem.changeMediaPath(decodeURIComponent(path), true);
    // 音频频素材会抛异常
    try {
      projectItem.setFootageInterpretation(interp);
    }
    catch (e) { }
    return result;

  },
  attachProxy: function (id, path, isHiRes) {
    var projectItem = PROJECT_ITEM_MAP[id]
    if (!projectItem) {
      return 'not exists'
    }
    if (projectItem.canProxy()) {
      return projectItem.attachProxy(decodeURIComponent(path), isHiRes || 0);
    } else {
      return 'not support'
    }
  },
  importFile: function (filePath) {
    var file = new File(filePath);
    if (file && file.exists) {
      app.project.importFiles(filePath, 1);
      var projectItems = getProjectItemsByMediaPath(filePath)
      file.close();
      return projectItems[0] && cloneProjectItem(projectItems[0]);
    } else {
      throw new Error('The file is not exist:' + filePath);
    }
  },
  render: function (data) {
    var outputPath = new File(data.outputPath);
    var presetPath = new File(data.presetPath);

    var extension = app.project.activeSequence.getExportFileExtension(presetPath.fsName);
    var fullFilePath = outputPath.fsName + "." + extension;
    var jobID = app.encoder.encodeSequence(app.project.activeSequence, fullFilePath, presetPath.fsName, app.encoder.ENCODE_IN_TO_OUT);
    app.encoder.startBatch();
    return jobID;
  }
}

/**
 * 从 bin 中找出指定路径的素材
 * @param {*} filePath 
 * @param {*} rootBin 
 * @returns 
 */
function getProjectItemsByMediaPath (filePath, rootBin) {
  return filterProjectItems(function (projectItem) {
    var mediaPath = projectItem.getMediaPath();
    return mediaPath === filePath;
  }, rootBin);
}

/**
 * 遍历 bin 中素材，过滤出符合条件的 projectItem
 * @param {Function} filterFn 过滤函数
 * @param {ProjectItem} rootBin 目标 bin | project.rootItem
 * @returns {ProjectItem[]}
 */
function filterProjectItems (filterFn, rootBin) {
  var result = [];
  var rootItem = rootBin || app.project.rootItem;
  function deepFun (inFolder) {
    for (var i = 0; i < inFolder.children.numItems; i++) {
      var projectItem = inFolder.children[i];
      if (filterFn(projectItem)) {
        result.push(projectItem);
      }
      if (projectItem && projectItem.type === ProjectItemType.BIN) {
        deepFun(projectItem);
      }
    }
  }
  deepFun(rootItem);
  return result
}

/**
 * 统一处理 clone projectItem
 * @param {*} projectItem 
 * @returns 
 */
function cloneProjectItem (projectItem) {
  var copiedProjectItem = $._.clone(projectItem)
  delete copiedProjectItem.getOverrideColorSpaceList // 这个数据太大了
  return copiedProjectItem
}


app.onItemAddedToProjectSuccess = function (project, item) {
  $._.emit('com.sobey.adobe.event.item-added', {
    project: project,
    item: item
  })
  var id = item.nodeId // 可以考虑从元数据中读取 考虑插件后打开如何构建这个map
  PROJECT_ITEM_MAP[id] = item
}

app.bind("onSourceClipSelectedInProjectPanel", function (project, item) {
  $._.emit('com.sobey.adobe.event.item-selected', {
    project: project,
    item: item
  })
});
app.bind("onItemsAddedToProjectSuccess", function (project, item) {
  $._.emit('com.sobey.adobe.event.items-added', {
    project: project,
    item: item
  })
});
app.bind('onProjectChanged', function (project, item) {
  $._.emit('com.sobey.adobe.event.project-added', {
    project: project,
    item: item
  })
});
app.bind("onActiveSequenceStructureChanged", function (project, item) {
  $._.emit('com.sobey.adobe.event.active-sequence-structure-changed', {
    project: project,
    item: item
  })
});
app.bind("onActiveSequenceChanged", function (project, item) {
  $._.emit('com.sobey.adobe.event.active-sequence-changed', {
    project: project,
    item: item
  })
});
app.bind('onActiveSequenceSelectionChanged', function (project, item) {
  $._.emit('com.sobey.adobe.event.active-sequence-selection-changed', {
    project: project,
    item: item
  })
});
app.bind('onSequenceActivated', function (project, item) {
  $._.emit('com.sobey.adobe.event.sequence-activated', {
    project: project,
    item: item
  })
});
app.bind('onActiveSequenceTrackItemRemoved', function (project, item) {
  $._.emit('com.sobey.adobe.event.active-sequence-track-item-removed', {
    project: project,
    item: item
  })
});
app.bind('onActiveSequenceTrackItemAdded', function (project, item) {
  $._.emit('com.sobey.adobe.event.active-sequence-track-item-added', {
    project: project,
    item: item
  })
});
app.bind('onActiveSequenceStructureChanged', function (project, item) {
  $._.emit('com.sobey.adobe.event.active-sequence-structure-changed', {
    project: project,
    item: item
  })
});

// 是否所有插件都有encoder
app.encoder.bind('onEncoderJobComplete', function (jobID, outputFilePath) {
  $._.emit('com.sobey.adobe.event.encoder-job-complete', {
    jobID: jobID,
    data: outputFilePath
  })
});

app.encoder.bind('onEncoderJobError', function (jobID, errorMessage) {
  $._.emit('com.sobey.adobe.event.encoder-job-error', {
    jobID: jobID,
    data: errorMessage
  })
});

app.encoder.bind('onEncoderJobProgress', function (jobID, progress) {
  $._.emit('com.sobey.adobe.event.encoder-job-progress', {
    jobID: jobID,
    data: progress
  })
});

app.encoder.bind('onEncoderJobQueued', function (jobID, data) {
  $._.emit('com.sobey.adobe.event.encoder-job-queued', {
    jobID: jobID,
    data: data
  })
});

app.encoder.bind('onEncoderJobCanceled', function (jobID, reason) {
  $._.emit('com.sobey.adobe.event.encoder-job-canceled', {
    jobID: jobID,
    data: reason
  })
});
console.log('pr jsx registed')
BridgeTalk.onReceive = function (talk) {
  try {
    if (!talk.type) return;
    $._.emit(talk.type, JSON.parse(talk.headers.info));
  }
  catch (e) { }
};